import path from 'path'
import electron from 'vite-plugin-electron'
import * as glob from 'glob'

export default () => {
  const electronRoot = path.join(process.cwd(), 'electron')

  return electron([
    {
      entry: path.join(electronRoot, 'main/index.ts'),
      vite: {
        build: {
          rollupOptions: {
            external: ['@prisma/client'],
            output: {
              format: 'cjs',
              dir: path.join(process.cwd(), 'dist/main'),
              entryFileNames: '[name].js',
              chunkFileNames: '[name].js'
            },
          }
        }
      }
    },
    {
      onstart(args) {
        args.reload()
      },
      vite: {
        build: {
          rollupOptions: {
            input: Object.fromEntries(
              glob
                .sync('preload/*.ts', {
                  ignore: ['**/*.d.ts'],
                  cwd: electronRoot
                })
                .map((filePath) => path.join(electronRoot, filePath))
                .map((filePath) => [path.basename(filePath, path.extname(filePath)), filePath])
            ),
            output: {
              format: 'cjs',
              dir: path.join(process.cwd(), 'dist/preload'),
              entryFileNames: '[name].js',
              chunkFileNames: '[name].js'
            },
          }
        }
      }
    }
  ])
}
